'use strict';

module.exports = app => {

  class UserService extends app.Service {

    constructor(ctx) {
      super(ctx);
      this.result = {
        err: '',
        code: -1,
        data: null,
      };
    }

    async login(phoneNO, code) {
      const result = {
        err: '',
        data: null,
      };
      const codeR = await this.app.redis.get(phoneNO);
      if (codeR) {
        if (code === codeR) {
          const user = await app.model.User.findOne({ phone: phoneNO });
          if (user) {
            const data = { id: user.id, phone: user.phone };
            user.dataValues.token = await this.createToken(data);
            result.data = user;
          }
        } else {
          result.err = '验证码不正确';
        }
      } else {
        result.err = '验证码已失效';
      }
      return result;
    }


    async getCode(phone) {
      const checkCode = await app.redis.get(phone);
      if (checkCode && typeof checkCode === 'string') {
        this.result.data = checkCode;
      } else {
        this.result.data = Math.random().toString().slice(-4);
        await app.redis.set(phone, this.result.data);
        await app.redis.expire(phone, 60 * 3);
      }
      return this.result;
    }

    // 通过id 获取用户信息
    async userInfo(id) {
      const user = await app.model.User.findById(id, { include: [
        {
          model: this.app.model.Role,
        },
      ] });
      this.result.data = user;
      return this.result;
    }

    async create(user) {
      const newUser = await app.model.User.create(user);
      const data = { id: newUser.id, phone: newUser.phone };
      if (newUser) {
        const token = await this.createToken(data);
        return token;
      }
    }

    async createToken(data) {
      return await app.jwt.sign(data, app.config.jwt.secret, {
        expiresIn: '12h',
      });
    }

    // 校验token
    verifyToken(token) {
      return new Promise((resolve, reject) => {
        app.jwt.verify(token, app.config.jwt.secret, function(err, decoded) {
          const result = {};
          if (err) {
            result.verify = false;
            result.message = err.message;
          } else {
            result.verify = true;
            result.message = decoded;
          }
          resolve(result);
        });
      });
    }
  }

  return UserService;
};
